<?php

class Admin_ModulesController extends Zend_Controller_Action
{
	// Do some checks here (including authorization)
	public function init()
	{
		parent::init();

		$sessAccount = Account_Model_Session::getAccount();
		if ($sessAccount === NULL) {
			$this->_redirect('/');
		}
		$gOpts = Kernel::getInstance()->getOptions();
		if (is_array($gOpts['site']) && is_array($gOpts['site']['administrator'])
			&& isset($gOpts['site']['administrator']['idname'])) {
			if ($sessAccount->getIdName() != $gOpts['site']['administrator']['idname']) {
				$this->_redirect('/');
			}
		}
	}


	public function indexAction()
	{
		$modules = Kernel::getInstance()->getModuleList();

		$viewModules = array();

		foreach ($modules as $mod) {
			$m = array();
			$m['idname'] = $mod->getIdName();
			$m['name'] = $mod->getName();
			$m['desc'] = $mod->getDescription();
			$m['active'] = $mod->getActive();
			$m['version'] = $mod->getVersion();
			if ($mod->hasValidInstalledVersion()) {
				$m['verInstalled'] = $mod->getInstalledVersion();
			} else {
				$m['verInstalled'] = '-';
			}
			$m['versMatch'] = $mod->checkVersions();
			if ($mod->getActive()) {
				$m['activeOpUrl'] = site_url_base('/admin/module/'. $mod->getIdName() .'/deactivate');
				$m['activeOp'] = 'Deactivate';
			} else {
				$m['activeOpUrl'] = site_url_base('/admin/module/'. $mod->getIdName() .'/activate');
				$m['activeOp'] = 'Activate';
			}
			$viewModules[] = (object)$m;
		}

		$this->view->moduleCount = count($viewModules);
		$this->view->moduleList = $viewModules;


		Kernel::getInstance()->setHeadTitle('Admin: Modules');

		$this->view->singleWidgetPageTitle = 'Module List';
		$this->view->singleWidgetPage = TRUE;
	}


	public function activateAction()
	{
		$idname = $this->_getParam('module_idname');
		if (empty($idname)) {
			//TODO: show error
			$this->_redirect('/admin/modules');
		}
		Admin_Model_Module::activate($idname, TRUE);
		$this->_redirect('/admin/modules');
	}

	public function deactivateAction()
	{
		$idname = $this->_getParam('module_idname');
		if (empty($idname)) {
			//TODO: show error
			$this->_redirect('/admin/modules');
		}
		Admin_Model_Module::activate($idname, FALSE);
		$this->_redirect('/admin/modules');
	}
}
